import { Component } from 'react'
import { inject, observer } from 'mobx-react'
import { View, Input, Picker } from '@tarojs/components'
import { AtList, AtListItem, AtInput, AtImagePicker, AtButton, AtIcon } from "taro-ui"
import { getAreaRange, getAreaIndexByNames } from '../../../utils/area'
import { getHeightRange } from '../../../utils/height';
import { getWeightRange } from '../../../utils/weight';
import { getIncomeList, incomeToText } from '../../../utils/income';
import { getMaritalStatusByIndex, getMaritalStatusByValue, getMaritalStatusList } from '../../../utils/maritalStatus'
import { getOccupationList, getOccupationValueByIndex } from '../../../utils/occupation';
import { getHouseList, getHouseByIndex } from '../../../utils/house';
import { getCarList, getValueTextByValue } from '../../../utils/car';
import { getEducationList, getEducationValueByIndex } from '../../../utils/education';
import { getExpectedMarriageTimeList, getExpectedMarriageTimeByIndex, getExpectedMarriageTimeTextByValue } from '../../../utils/expectedMarriageTime'
import Taro from '@tarojs/taro'
import ImageCropper from '../../test/ImageCropper'
import fileUpload from '../../../utils/qiniu/upload'

import './index.less'

const HEIGHT_RANGE = getHeightRange({ hasEmpty: false, multiple: false });
const WEIGHT_RANGE = getWeightRange({ hasEmpty: false, multiple: false });
const MARITAL_STATUS_RANGE = getMaritalStatusList({ hasEmpty: false })
const INCOME_RANGE = getIncomeList({ hasEmpty: false });
const OCCUOATION_RANGE = getOccupationList({ hasEmpty: false });
const HOUSE_RANGE = getHouseList({ hasEmpty: false });
const CAR_RANGE = getCarList({ hasEmpty: false });
const EXPECTED_MARRIAGE_TIME_RANGE = getExpectedMarriageTimeList({ hasEmpty: false });
const EDUCATION_RANGE = getEducationList({ hasEmpty: false });

const uploadFiles = async (files = []) => {
	const allPromise = files.map(item => {
		// 如果有file 则认为是新文件需要上传
		if (item.file) {
			return fileUpload.uploadImg(item.url)
		}

		return {
			path: item.url
		}
	})

	const resp = await Promise.all(allPromise);
	console.log(resp, 2222222333334444)
	return resp
}

@inject('store')
@observer
export default class Index extends Component {
	state = {
		birthday: null,
		workAreaRange: [],			// 工作地
    workAreaValue: [0, 0, 0],
		workAreaProvince: '',
		workAreaCity: '',
		maritalStatus: "",
		workAreaRegion: '',
		homeAreaRange: [],			// 家乡
    homeAreaValue: [0, 0, 0],
		homeProvince: '',
		homeCity: '',
		homeRegion: '',
		height: null,
		weight: null,
		minIncome: null,
		maxIncome: null,
		occupation: null,
		house: null,
		car: null,
		wxNumber: "",
		expectedMarriageTime: null,
		education: "", //学历
		avatar: '', //主图
		lifePhotos: [
		], // 生活照
		cropperVisible: false,
		tempAvatar: ""
	}

  componentWillMount () { }

  componentDidMount () {
		this.getWorkAreaRange();
		this.getHomeAreaRange();
		this.getAccountBaseInfo();
	}

	getAccountBaseInfo = async () => {
    const { id } = this.props;
    // TODO 获取用户详情信息
		const { success, data, msg } = await Taro.request({
			method: 'get',
			url: '/api/account/basic/info/detail',
			data: {
        accountId: id
      }
		})
    if (success && data) {
			const {
				birthday,
				height,
				weight,
				minIncome,
				maxIncome,
				occupation,
				house,
				car,
				expectedMarriageTime,
				wxNumber,
				education,
				avatar,
				lifePhotos,
				workAreaCity,
				workAreaProvince,
				workAreaRegion,
				homeProvince,
				homeCity,
				homeRegion,
				maritalStatus
			} = data || {}

			const workIndexs = await getAreaIndexByNames({ hasEmpty: false, names: [ workAreaProvince, workAreaCity, workAreaRegion ] })
			const workResp = await getAreaRange({ hasEmpty: false, value: workIndexs })

			const homeIndexs = await getAreaIndexByNames({ hasEmpty: false, names: [ homeProvince, homeCity, homeRegion ] })
			const homeResp = await getAreaRange({ hasEmpty: false, value: homeIndexs })
			
      this.setState({
        birthday,
				height,
				weight,
				minIncome,
				maxIncome,
				occupation,
				house,
				car,
				expectedMarriageTime,
				wxNumber,
				education,
				avatar,
				lifePhotos,
				workAreaCity,
				workAreaProvince,
				workAreaRegion,
				workAreaRange: workResp.ranges,
				workAreaValue: workIndexs,
				homeProvince,
				homeCity,
				homeRegion,
				homeAreaRange: homeResp.ranges,
				homeAreaValue: homeIndexs,
				maritalStatus
      })
    }
  }

  componentWillUnmount () { }

  componentDidShow () { }

  componentDidHide () { }

	onBirtydayChange = (e) => {
		console.log(e, 1111111)
		this.setState({
			birthday: e.target.value
		})
	}

	getWorkAreaRange = async () => {
		const resp = await getAreaRange({ hasEmpty: false, value: [] })
    this.setState({
      workAreaRange: resp.ranges,
      workAreaValue: [],
    })
  }

  onWorkAreaChange = (e) => {
    const { value } = e.detail
    const { workAreaRange } = this.state
    const provinceIndex = value?.[0] || 0;
    const citieIndex = value?.[1] || 0;
    const areaIndex = value?.[2] || 0;
    const provinceName = workAreaRange?.[0]?.[provinceIndex];
    const cityName = workAreaRange?.[1]?.[citieIndex];
    const areaName = workAreaRange?.[2]?.[areaIndex];
    console.log(provinceName, cityName, areaName, 66666666)
		this.setState({
			workAreaValue: value,
			workAreaProvince: provinceName,
			workAreaCity: cityName,
			workAreaRegion: areaName,
		})
  }

  onWorkAreaColumnChange = async (e) => {
    console.log('onWorkAreaColumnChange', 222222, e)
    const { workAreaValue = [0, 0, 0] } = this.state;
    const { column, value } = e.detail;
    let currentValue = []
    // 省变了
    if (column === 0) {
      currentValue = [value, 0, 0];
    } else if (column === 1) {
      currentValue = [workAreaValue[0] || 0, value, 0];
    } else {
      currentValue = [workAreaValue[0] || 0, workAreaValue[1] || 0, value];
    }
    const resp = await getAreaRange({ hasEmpty: false, value: currentValue })
    this.setState({
      workAreaRange: resp.ranges,
      workAreaValue: currentValue,
    })
  }

	getHomeAreaRange = async () => {
		const resp = await getAreaRange({ hasEmpty: false, value: [] })
    this.setState({
      homeAreaRange: resp.ranges,
      homeAreaValue: [],
    })
  }


  onMaritalStatusChange = (e) => {
		console.log('onMaritalStatusChange:', e);
    const { value } = e.detail;
    const status =  getMaritalStatusByIndex({ hasEmpty: false, index: +value });
    console.log('status: ', status);
    this.setState({
      maritalStatus: status?.value
    })
  }

  onHomeAreaChange = (e) => {
    const { value } = e.detail
    const { homeAreaRange } = this.state
    const provinceIndex = value?.[0] || 0;
    const citieIndex = value?.[1] || 0;
    const areaIndex = value?.[2] || 0;
    const provinceName = homeAreaRange?.[0]?.[provinceIndex];
    const cityName = homeAreaRange?.[1]?.[citieIndex];
    const areaName = homeAreaRange?.[2]?.[areaIndex];
    console.log(provinceName, cityName, areaName, 66666666)
		this.setState({
			homeAreaValue: value,
			homeProvince: provinceName,
			homeCity: cityName,
			homeRegion: areaName,
		})
  }

  onHomeAreaColumnChange = async (e) => {
    console.log('onHomeAreaColumnChange', 222222, e)
    const { homeAreaValue = [0, 0, 0] } = this.state;
    const { column, value } = e.detail;
    let currentValue = []
    // 省变了
    if (column === 0) {
      currentValue = [value, 0, 0];
    } else if (column === 1) {
      currentValue = [homeAreaValue[0] || 0, value, 0];
    } else {
      currentValue = [homeAreaValue[0] || 0, homeAreaValue[1] || 0, value];
    }
    const resp = await getAreaRange({ hasEmpty: false, value: currentValue })
    this.setState({
      homeAreaRange: resp.ranges,
      homeAreaValue: currentValue,
    })
  }

	onHeightChange = (e) => {
		console.log('onHeightChange:', e);
    const { value } = e.detail;
		this.setState({
			height: HEIGHT_RANGE[value]
		})
  }

	onWeightChange = (e) => {
		console.log('onWeightChange:', e);
    const { value } = e.detail;
		this.setState({
			weight: WEIGHT_RANGE[value]
		})
  }

	onIncomeChange = (e) => {
		console.log('onIncomeChange:', e);
    const { value } = e.detail;
		const { min, max } = INCOME_RANGE[value];
		this.setState({
			minIncome: min,
			maxIncome: max,
		})
  }

	onOccupationChange = (e) => {
		console.log('onOccupationChange:', e);
    const { value } = e.detail;
		const occupation = getOccupationValueByIndex({ hasEmpty: false, index: value });
		this.setState({
			occupation
		})
  }

	onHouseChange = (e) => {
		console.log('onHouseChange:', e);
    const { value } = e.detail;
		const houseObj = getHouseByIndex({ hasEmpty: false, index: +value });
		
		this.setState({
			house: houseObj.value
		})
  }

	onCarChange = (e) => {
		console.log('onCarChange:', e);
    const { value } = e.detail;
		const carObj = getHouseByIndex({ hasEmpty: false, index: +value });
		
		this.setState({
			car: carObj.value
		})
  }

	onWxNumber = (e) => {
		console.log("onWxNumber", e)
		this.setState({
			wxNumber: e.detail.value
		})
	}

	onExpectedMarriageTimeChange = (e) => {
		console.log('onExpectedMarriageTimeChange:', e);
    const { value } = e.detail;
		const obj = getExpectedMarriageTimeByIndex({ hasEmpty: false, index: +value });
		
		this.setState({
			expectedMarriageTime: obj.value
		})
	}

	onAvatarChange = async (e) => {
		console.log(e, 1122334455)
		const url = e?.[0]?.url
		
		if (url) {
			this.setState({
				tempAvatar: url,
				cropperVisible: true
			})
			// const resp = await fileUpload.uploadImg(url)
			// console.log(resp?.[0]?.path, resp, 2222222)
			// this.setState({
			// 	avatar: resp?.path
			// })
		} else {
			this.setState({
				avatar: ''
			})
		}
	}

	onAvatarCropper = async (path) => {
		console.log(path, 888888888)
		const resp = await fileUpload.uploadImg(path)

		this.setState({
			avatar: resp?.path,
			tempAvatar: '',
			cropperVisible: false
		})
		console.log(path, 111222333444)
	}

	onLifePhotosChange = async (files, operationType, index) => {
		console.log("onLifePhotosChange:", files, operationType, index)
		const allFiles = await uploadFiles(files)
		console.log(allFiles, 1111122222233333)
		this.setState({
			lifePhotos: allFiles.map(item => item.path)
		})
	}

	onEducationChange = (e) => {
		console.log('onEducationChange:', e);
    const { value } = e.detail;
		const education = getEducationValueByIndex({ hasEmpty: false, index: value });
		this.setState({
			education
		})
  }

	handleSubmit = async () => {
		const {
			birthday,
			workAreaProvince,
			workAreaCity,
			workAreaRegion,
			homeProvince,
			homeCity,
			homeRegion,
			height,
			weight,
			minIncome,
			maxIncome,
			occupation,
			house,
			car,
			wxNumber,
			expectedMarriageTime,
			avatar,
			lifePhotos,
			education,
			maritalStatus
		} = this.state;

		if (!birthday) {
			Taro.showToast({
				title: '生日不能为空',
				icon: 'none',
				duration: 2000
			})
			return
		}

		if (!workAreaProvince) {
			Taro.showToast({
				title: '请选择工作地',
				icon: 'none',
				duration: 2000
			})
			return
		}

		if (!homeProvince) {
			Taro.showToast({
				title: '请选择户籍所在地',
				icon: 'none',
				duration: 2000
			})
			return
		}


		if (!maritalStatus) {
			Taro.showToast({
				title: '请选择婚婚姻状态',
				icon: 'none',
				duration: 2000
			})
			return
		}

		if (!height) {
			Taro.showToast({
				title: '身高不能为空',
				icon: 'none',
				duration: 2000
			})
			return
		}

		if (!weight) {
			Taro.showToast({
				title: '体重不能为空',
				icon: 'none',
				duration: 2000
			})
			return
		}

		if (!minIncome && !maxIncome) {
			Taro.showToast({
				title: '请选择收入',
				icon: 'none',
				duration: 2000
			})
			return
		}

		if (!occupation) {
			Taro.showToast({
				title: '请选择职业',
				icon: 'none',
				duration: 2000
			})
			return
		}

		if (!Number.isInteger(car)) {
			Taro.showToast({
				title: '请选择汽车',
				icon: 'none',
				duration: 2000
			})
			return
		}

		if (!Number.isInteger(house)) {
			Taro.showToast({
				title: '请选择房产',
				icon: 'none',
				duration: 2000
			})
			return
		}

		if (!Number.isInteger(expectedMarriageTime)) {
			Taro.showToast({
				title: '请选择期望结婚时间',
				icon: 'none',
				duration: 2000
			})
			return
		}

		if (!avatar) {
			Taro.showToast({
				title: '请上传头图',
				icon: 'none',
				duration: 2000
			})
			return
		}

		if (!wxNumber) {
			Taro.showToast({
				title: '微信好不能为空',
				icon: 'none',
				duration: 2000
			})
			return
		}

		if (!education) {
			Taro.showToast({
				title: '学历不能为空',
				icon: 'none',
				duration: 2000
			})
			return
		}

		const params = {
			accountId: this.props.id,
			birthday,
			workAreaProvince,
			workAreaCity,
			workAreaRegion,
			homeProvince,
			homeCity,
			homeRegion,
			height,
			weight,
			minIncome,
			maxIncome,
			occupation,
			house,
			car,
			wxNumber,
			expectedMarriageTime,
			avatar,
			lifePhotos,
			education,
			maritalStatus
		};

		const { success, data, msg } = await Taro.request({
			method: 'post',
			url: '/api/account/basic/info',
			data: params
		})

		if (success) {
			this.props.onSuccess && this.props.onSuccess()
			Taro.showToast({
				title: '提交成功',
				icon: 'success',
				duration: 2000
			})
		} else {
			Taro.showToast({
				title: msg,
				icon: 'none',
				duration: 2000
			})
		}

		console.log("提交的参数是：", params)
	}

  render () {
		const {
			birthday,
			workAreaRange,
			workAreaValue,
			workAreaProvince,
			workAreaCity,
			workAreaRegion,
			homeAreaRange,
			homeAreaValue,
			homeProvince,
			homeCity,
			homeRegion,
			height,
			weight,
			minIncome,
			maxIncome,
			occupation,
			house,
			car,
			expectedMarriageTime,
			wxNumber,
			avatar,
			lifePhotos,
			education,
			cropperVisible,
			maritalStatus
		} = this.state
		const workAreaText = workAreaProvince&&workAreaCity&&workAreaRegion ? `${workAreaProvince}${workAreaCity}${workAreaRegion}` : '请选择'
		const homeAreaText = homeProvince&&homeCity&&homeRegion ? `${homeProvince}${homeCity}${homeRegion}` : '请选择'
		const incomeText = incomeToText(minIncome, maxIncome);
		const houseObj = getHouseByIndex({ hasEmpty: false, index: house });
		const carText = getValueTextByValue({ hasEmpty: false, value: car });
		const expectedMarriageTimeText = getExpectedMarriageTimeTextByValue({ hasEmpty: false, value: expectedMarriageTime });
		const avatarFiles = avatar ? [{ url: avatar }] : []
		const lifePhotosFiles = lifePhotos.map(url => {
			return {
				url
			}
		})

		const maritalStatusText = getMaritalStatusByValue({ value: maritalStatus })?.name;

		return (
      <View className='basic-info'>

				<View className='form'>
					<Picker mode='date' value={birthday} onChange={this.onBirtydayChange}>
						<View className='form-item'>
							<View className='form-item-title require'>
								生日
							</View>
							<View className='form-item-value'>
								{birthday || "请选择"}
							</View>
							<View className='form-item-arrow'>
								<AtIcon value='chevron-right' size='22' color='#999'></AtIcon>
							</View>
						</View>
					</Picker>
					<Picker
						mode='multiSelector'
						range={workAreaRange}
						value={workAreaValue}
						onChange={this.onWorkAreaChange}
						onColumnChange={this.onWorkAreaColumnChange}>
						<View className='form-item'>
							<View className='form-item-title require'>
								居住地
							</View>
							<View className='form-item-value'>
								{workAreaText || "请选择"}
							</View>
							<View className='form-item-arrow'>
								<AtIcon value='chevron-right' size='22' color='#999'></AtIcon>
							</View>
						</View>
					</Picker>
					<Picker
						mode='multiSelector'
						range={homeAreaRange}
						value={homeAreaValue}
						onChange={this.onHomeAreaChange}
						onColumnChange={this.onHomeAreaColumnChange}>
						<View className='form-item'>
							<View className='form-item-title require'>
								户籍
							</View>
							<View className='form-item-value'>
								{homeAreaText || "请选择"}
							</View>
							<View className='form-item-arrow'>
								<AtIcon value='chevron-right' size='22' color='#999'></AtIcon>
							</View>
						</View>
					</Picker>
					<Picker
						mode='selector'
						range={MARITAL_STATUS_RANGE}
						onChange={this.onMaritalStatusChange}
						rangeKey="name"
					>
						<View className='form-item'>
							<View className='form-item-title require'>
								婚姻状态
							</View>
							<View className='form-item-value'>
								{maritalStatusText || '请选择'}
							</View>
							<View className='form-item-arrow'>
								<AtIcon value='chevron-right' size='22' color='#999'></AtIcon>
							</View>
						</View>
					</Picker>
					<Picker
						mode='selector'
						range={HEIGHT_RANGE}
						onChange={this.onHeightChange}
					>
						<View className='form-item'>
							<View className='form-item-title require'>
								身高
							</View>
							<View className='form-item-value'>
								{height ? `${height}cm` : '请选择'}
							</View>
							<View className='form-item-arrow'>
								<AtIcon value='chevron-right' size='22' color='#999'></AtIcon>
							</View>
						</View>
					</Picker>

					<Picker
						mode='selector'
						range={WEIGHT_RANGE}
						onChange={this.onWeightChange}
					>
						<View className='form-item'>
							<View className='form-item-title require'>
								体重
							</View>
							<View className='form-item-value'>
								{weight ? `${weight}kg` : '请选择'}
							</View>
							<View className='form-item-arrow'>
								<AtIcon value='chevron-right' size='22' color='#999'></AtIcon>
							</View>
						</View>
					</Picker>

					<Picker
						mode='selector'
						range={INCOME_RANGE}
						onChange={this.onIncomeChange}
						rangeKey="name"
					>
						<View className='form-item'>
							<View className='form-item-title require'>
								收入
							</View>
							<View className='form-item-value'>
								{incomeText || '请选择'}
							</View>
							<View className='form-item-arrow'>
								<AtIcon value='chevron-right' size='22' color='#999'></AtIcon>
							</View>
						</View>
					</Picker>

					<Picker
						mode='selector'
						range={OCCUOATION_RANGE}
						onChange={this.onOccupationChange}
					>
						<View className='form-item'>
							<View className='form-item-title require'>
								职业
							</View>
							<View className='form-item-value'>
								{occupation || '请选择'}
							</View>
							<View className='form-item-arrow'>
								<AtIcon value='chevron-right' size='22' color='#999'></AtIcon>
							</View>
						</View>
					</Picker>

					<Picker
						mode='selector'
						range={HOUSE_RANGE}
						onChange={this.onHouseChange}
						rangeKey="name"
					>
						<View className='form-item'>
							<View className='form-item-title require'>
							房子
							</View>
							<View className='form-item-value'>
								{houseObj?.name || '请选择'}
							</View>
							<View className='form-item-arrow'>
								<AtIcon value='chevron-right' size='22' color='#999'></AtIcon>
							</View>
						</View>
					</Picker>

					<Picker
						mode='selector'
						range={CAR_RANGE}
						onChange={this.onCarChange}
						rangeKey="name"
					>
						<View className='form-item'>
							<View className='form-item-title require'>
								车
							</View>
							<View className='form-item-value'>
								{carText || '请选择'}
							</View>
							<View className='form-item-arrow'>
								<AtIcon value='chevron-right' size='22' color='#999'></AtIcon>
							</View>
						</View>
					</Picker>
					
					<Picker
						mode='selector'
						range={EXPECTED_MARRIAGE_TIME_RANGE}
						onChange={this.onExpectedMarriageTimeChange}
						rangeKey="name"
					>
						<View className='form-item'>
							<View className='form-item-title require'>
								期望结婚时间
							</View>
							<View className='form-item-value'>
								{expectedMarriageTimeText || '请选择'} 
							</View>
							<View className='form-item-arrow'>
								<AtIcon value='chevron-right' size='22' color='#999'></AtIcon>
							</View>
						</View>
					</Picker>

					<View className='form-item'>
						<View className='form-item-title require'>
							微信号
						</View>
						<View className='form-item-value'>
							<Input
								type='text'
								placeholder='请输入微信号'
								value={wxNumber}
								onInput={this.onWxNumber}
							/>
						</View>
					</View>

					<Picker
						mode='selector'
						range={EDUCATION_RANGE}
						onChange={this.onEducationChange}
					>
						<View className='form-item'>
							<View className='form-item-title require'>
							学历
							</View>
							<View className='form-item-value'>
								{education || '请选择'}
							</View>
							<View className='form-item-arrow'>
								<AtIcon value='chevron-right' size='22' color='#999'></AtIcon>
							</View>
						</View>
					</Picker>

					<View className='form-item row'>
						<View className='form-item-title require'>
							头像
						</View>
					</View>

					<AtImagePicker
						files={avatarFiles}
						onChange={this.onAvatarChange}
						multiple={false}
						showAddBtn={avatarFiles.length == 0}
					/>
					<View className='form-item row' style={{ marginTop: '16px' }}>
						<View className='form-item-title'>
							生活照
						</View>
					</View>
					<AtImagePicker
						files={lifePhotosFiles}
						onChange={this.onLifePhotosChange}
						multiple={true}
						showAddBtn={lifePhotos.length < 9}
					/>
				</View>


				<View className='submit-btn' onClick={this.handleSubmit}>
					提交
				</View>

				{cropperVisible &&
					<ImageCropper
						visible={cropperVisible}
						image={this.state.tempAvatar}
						onClose={() => {
							this.setState({
								cropperVisible: false
							})
						}}
						onOk={this.onAvatarCropper}
					/>
				}
      </View>
    )
  }
}